<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="产品名称" prop="productName">
        <el-input v-model="queryParams.productName" placeholder="请输入产品名称" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="设备类型" prop="deviceType">
        <el-select v-model="queryParams.deviceType" placeholder="请选择设备类型" clearable>
          <el-option v-for="dict in dict.type.iot_device_type" :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="传输协议" prop="transProtocol">
        <el-select v-model="queryParams.transProtocol" placeholder="请选择传输协议" clearable>
          <el-option v-for="dict in dict.type.iot_trans_protocol" :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <!-- <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['iot:product:edit']">修改</el-button> -->
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['iot:product:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <!-- <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['iot:product:export']">导出</el-button> -->
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="productList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="产品名称" align="center" prop="productName"/>
      <el-table-column label="设备类型" align="center" prop="deviceType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.iot_device_type" :value="scope.row.deviceType"/>
        </template>
      </el-table-column>
      <el-table-column label="传输协议" align="center" prop="transProtocol">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.iot_trans_protocol" :value="scope.row.transProtocol"/>
        </template>
      </el-table-column>
      <el-table-column label="启用授权" align="center" prop="isAuthRequired">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.isAuthRequired"/>
        </template>
      </el-table-column>
      <el-table-column label="认证方式" align="center" prop="authMethod">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.iot_auth_method" :value="scope.row.authMethod"/>
        </template>
      </el-table-column>
      <el-table-column label="产品编号" align="center" prop="id"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['iot:product:edit']">查看</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['iot:product:remove']">删除</el-button>
          <el-button size="mini" type="text" icon="el-icon-key" @click="handleAuth(scope.row)" v-hasPermi="['iot:device:list']" v-if="scope.row.isAuthRequired === 1">授权</el-button>
          <!-- <el-button size="mini" type="text" icon="el-icon-s-operation" @click="handleModel(scope.row)" v-hasPermi="['iot:model:list']">物模型</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList"/>

    <!-- 添加或修改产品对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body @close="cancel">
      <el-tabs v-model="activeName">
        <!-- 基本信息 -->
        <el-tab-pane label="基本信息" name="basic">
          <el-form ref="form" :model="form" :rules="rules" label-width="120px">
            <el-row>
              <el-col :span="12">
                <el-form-item label="产品名称" prop="productName">
                  <el-input v-model="form.productName" placeholder="请输入产品名称"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="产品分类" prop="deviceType">
                  <el-select v-model="form.deviceType" placeholder="请选择产品分类">
                    <el-option v-for="dict in dict.type.iot_device_type" :key="dict.value" :label="dict.label" :value="dict.value"/>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="设备类型" prop="deviceCategory">
                  <el-select v-model="form.deviceCategory" placeholder="请选择设备类型">
                    <el-option label="直连设备" value="direct"/>
                    <el-option label="网关设备" value="gateway"/>
                    <el-option label="网关子设备" value="gateway_child"/>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="传输协议" prop="transProtocol">
                  <el-select v-model="form.transProtocol" placeholder="请选择传输协议">
                    <el-option v-for="dict in dict.type.iot_trans_protocol" :key="dict.value" :label="dict.label" :value="dict.value"/>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="联网方式" prop="networkMethod">
                  <el-select v-model="form.networkMethod" placeholder="请选择联网方式">
                    <el-option label="WIFI" value="wifi"/>
                    <el-option label="蜂窝网络" value="cellular"/>
                    <el-option label="以太网" value="ethernet"/>
                    <el-option label="其他" value="other"/>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="启用授权" prop="isAuthRequired">
                  <el-radio-group v-model="form.isAuthRequired">
                    <el-radio :label="1">是</el-radio>
                    <el-radio :label="0">否</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12" v-if="form.isAuthRequired === 1">
                <el-form-item label="认证方式" prop="authMethod">
                  <el-select v-model="form.authMethod" placeholder="请选择认证方式">
                    <el-option v-for="dict in dict.type.iot_auth_method" :key="dict.value" :label="dict.label" :value="dict.value"/>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="产品编号" prop="id">
                  <el-input v-model="form.id" disabled/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="MQTT账号" prop="mqttAccount">
                  <el-input v-model="form.mqttAccount" placeholder="请输入MQTT账号"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="MQTT密码" prop="mqttPassword">
                  <el-input v-model="form.mqttPassword" placeholder="请输入MQTT密码" show-password/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="产品密钥" prop="productKey">
                  <el-input v-model="form.productKey" placeholder="请输入产品密钥" show-password/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="产品图片" prop="productImage">
              <image-upload v-model="form.productImage"/>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 产品模型 -->
        <el-tab-pane label="产品模型" name="model" :disabled="!form.id">
          <div class="model-container">
            <div class="model-header">
              <el-row :gutter="10">
                <el-col :span="8">
                  <el-select v-model="modelQuery.type" placeholder="请选择物模型类型" clearable>
                    <el-option label="属性" value="property"/>
                    <el-option label="事件" value="event"/>
                    <el-option label="服务" value="service"/>
                  </el-select>
                </el-col>
                <el-col :span="8">
                  <el-select v-model="modelQuery.isHistory" placeholder="请选择是否历史存储" clearable>
                    <el-option label="是" :value="1"/>
                    <el-option label="否" :value="0"/>
                  </el-select>
                </el-col>
                <el-col :span="8">
                  <el-button type="primary" icon="el-icon-plus" @click="handleAddModel">新增</el-button>
                  <el-button type="success" icon="el-icon-download" @click="handleImportModel">导入</el-button>
                </el-col>
              </el-row>
            </div>
            <el-table :data="modelList" style="width: 100%">
              <el-table-column prop="name" label="名称"/>
              <el-table-column prop="identifier" label="标识符"/>
              <el-table-column prop="type" label="类型">
                <template slot-scope="scope">
                  <el-tag v-if="scope.row.type === 'property'">属性</el-tag>
                  <el-tag type="success" v-else-if="scope.row.type === 'event'">事件</el-tag>
                  <el-tag type="warning" v-else>服务</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="dataType" label="数据类型"/>
              <el-table-column prop="isRealtime" label="实时监测">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.isRealtime"/>
                </template>
              </el-table-column>
              <el-table-column prop="isHistory" label="历史存储">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.isHistory"/>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="200">
                <template slot-scope="scope">
                  <el-button size="mini" type="text" icon="el-icon-edit" @click="handleEditModel(scope.row)">修改</el-button>
                  <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDeleteModel(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>

        <!-- 设备授权 -->
        <el-tab-pane label="设备授权" name="auth" :disabled="!form.id">
          <div class="auth-container">
            <div class="auth-header">
              <el-row :gutter="10">
                <el-col :span="16">
                  <el-input v-model="authQuery.keyword" placeholder="请输入授权码或设备编号" clearable>
                    <el-button slot="append" icon="el-icon-search" @click="searchAuth"/>
                  </el-input>
                </el-col>
                <el-col :span="8">
                  <el-button type="primary" icon="el-icon-plus" @click="handleAddAuth">新增</el-button>
                  <el-button type="success" icon="el-icon-download" @click="handleExportAuth">导出</el-button>
                </el-col>
              </el-row>
            </div>
            <el-table :data="authList" style="width: 100%">
              <el-table-column prop="authCode" label="授权码"/>
              <el-table-column prop="deviceCode" label="设备编号"/>
              <el-table-column prop="status" label="状态">
                <template slot-scope="scope">
                  <el-tag type="success" v-if="scope.row.status === 1">已使用</el-tag>
                  <el-tag v-else>未使用</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="authTime" label="授权时间" width="180">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.authTime) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="200">
                <template slot-scope="scope">
                  <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDeleteAuth(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{ form.id ? '修改' : '新增' }}</el-button>
      </div>
    </el-dialog>

    <!-- 添加产品弹出框组件 -->
    <product-add ref="productAdd" @success="handleAddSuccess"/>
  </div>
</template>

<script>
import { listProduct, getProduct, delProduct, addProduct, updateProduct } from "@/api/iot/product";
import ProductAdd from "./add";

export default {
  name: "Product",
  dicts: ['sys_yes_no', 'iot_device_type', 'iot_trans_protocol', 'iot_auth_method'],
  components: {
    ProductAdd
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 产品表格数据
      productList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productName: null,
        deviceType: null,
        transProtocol: null
      },
      // 表单参数
      form: {},
      // 新增数据
      activeName: 'basic',
      // 物模型查询参数
      modelQuery: {
        type: null,
        isHistory: null
      },
      // 物模型列表数据
      modelList: [],
      // 授权查询参数
      authQuery: {
        keyword: null
      },
      // 授权列表数据
      authList: [],
      // 表单校验规则
      rules: {
        productName: [
          { required: true, message: "产品名称不能为空", trigger: "blur" }
        ],
        deviceType: [
          { required: true, message: "产品分类不能为空", trigger: "change" }
        ],
        deviceCategory: [
          { required: true, message: "设备类型不能为空", trigger: "change" }
        ],
        transProtocol: [
          { required: true, message: "传输协议不能为空", trigger: "change" }
        ],
        networkMethod: [
          { required: true, message: "联网方式不能为空", trigger: "change" }
        ],
        authMethod: [
          { required: true, message: "认证方式不能为空", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询产品列表 */
    getList() {
      this.loading = true;
      listProduct(this.queryParams).then(response => {
        this.productList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        productName: null,
        deviceType: null,
        deviceCategory: null,
        transProtocol: null,
        networkMethod: null,
        isAuthRequired: 0,
        authMethod: null,
        mqttAccount: null,
        mqttPassword: null,
        productKey: null,
        productImage: null,
        remark: null
      };
      this.resetForm("form");
      this.activeName = 'basic';
      this.modelList = [];
      this.authList = [];
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$refs.productAdd.show();
    },
    /** 新增成功回调 */
    handleAddSuccess() {
      this.getList();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const id = row.id || this.ids;
      this.$router.push({ 
        path: '/iot/product/form', 
        query: { id: id }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateProduct(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProduct(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.form.id = response.data.id;
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除产品编号为"' + ids + '"的数据项？').then(function() {
        return delProduct(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('iot/product/export', {
        ...this.queryParams
      }, `product_${new Date().getTime()}.xlsx`)
    },
    /** 授权按钮操作 */
    handleAuth(row) {
      const id = row.id
      this.$router.push({
        path: '/iot/device/auth',
        query: {
          productId: id
        }
      })
    },
    /** 物模型按钮操作 */
    handleModel(row) {
      const id = row.id
      this.$router.push({
        path: '/iot/model',
        query: {
          productId: id
        }
      })
    },
    /** 物模型相关方法 */
    handleAddModel() {
      // TODO: 实现新增物模型的逻辑
    },
    handleImportModel() {
      // TODO: 实现导入物模型的逻辑
    },
    handleEditModel(row) {
      // TODO: 实现编辑物模型的逻辑
    },
    handleDeleteModel(row) {
      // TODO: 实现删除物模型的逻辑
    },
    /** 设备授权相关方法 */
    searchAuth() {
      // TODO: 实现搜索授权的逻辑
    },
    handleAddAuth() {
      // TODO: 实现新增授权的逻辑
    },
    handleExportAuth() {
      // TODO: 实现导出授权的逻辑
    },
    handleDeleteAuth(row) {
      // TODO: 实现删除授权的逻辑
    },
    /** 加载授权列表 */
    loadAuthList() {
      // TODO: 实现加载授权列表的逻辑
    },
    /** 加载物模型列表 */
    loadModelList() {
      // TODO: 实现加载物模型列表的逻辑
    }
  },
  /** 监听启用授权的变化 */
  watch: {
    'form.isAuthRequired'(newVal) {
      if (newVal === 1) {
        // 如果启用授权，重置授权列表
        this.authList = [];
      }
    }
  }
};
</script>

<style scoped>
.model-container,
.auth-container {
  padding: 20px;
}

.model-header,
.auth-header {
  margin-bottom: 20px;
}
</style> 